/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.japo.java.samples;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;

/**
 *
 * @author Carlos Amores
 */
class GEV extends WindowAdapter {

    private final String F_BLOQUEO = "instancia.lock";
    private IGU igu;

    GEV(IGU igu) {
        this.igu = igu;
    }

    @Override
    public void windowOpened(WindowEvent we) {
        try {
            activarInstancia();
        } catch (Exception e) {
            terminarPrograma();
        }
    }

    @Override
    public void windowClosing(WindowEvent we) {
        try {
            desactivarInstancia();
        } catch (Exception e) {
            terminarPrograma();
        }
    }

    private void terminarPrograma() {
        igu.setVisible(true);
        igu.dispose();
        System.exit(0);
    }

    private void activarInstancia() throws Exception {
        File f = new File(F_BLOQUEO);

        boolean existeOK = f.exists();

        if (!existeOK) {
            f.createNewFile();
        } else {
            throw new Exception("Ya hay otra instancia");
        }
    }

    private void desactivarInstancia() throws Exception {
        File f = new File(F_BLOQUEO);

        boolean existeOK = f.exists();

        if (existeOK) {
            f.delete();
        } else {
            throw new Exception("Problemas con la anulación");
        }
    }
}
